const Mock = require('mockjs')

const userData = Mock.mock({
  'users|20': [{
    'id|+1': 1,
    username: '@cname',
    'role|1': ['admin', 'waiter', 'chef', 'manager'],
    phone: /^1[3-9]\d{9}$/,
    'status|1': [0, 1],
    createTime: '@datetime',
    email: '@email'
  }]
})

module.exports = [
  // 获取用户列表
  {
    url: '/api/user/list',
    method: 'get',
    response: () => {
      return {
        code: 200,
        msg: '操作成功',
        data: userData.users
      }
    }
  },
  
  // 根据ID获取用户信息
  {
    url: RegExp('/api/user/.*'),
    method: 'get',
    response: ({ url }) => {
      const id = url.split('/').pop()
      const user = userData.users.find(u => u.id == id)
      if (user) {
        return {
          code: 200,
          msg: '操作成功',
          data: user
        }
      } else {
        return {
          code: 404,
          msg: '用户不存在'
        }
      }
    }
  },
  
  // 新增用户
  {
    url: '/api/user/add',
    method: 'post',
    response: ({ body }) => {
      const newUser = {
        id: userData.users.length + 1,
        username: body.username,
        role: body.role,
        phone: body.phone,
        status: body.status,
        createTime: new Date().toLocaleString('zh-CN'),
        email: body.email
      }
      userData.users.push(newUser)
      return {
        code: 200,
        msg: '操作成功',
        data: null
      }
    }
  },
  
  // 更新用户
  {
    url: '/api/user/update',
    method: 'put',
    response: ({ body }) => {
      const index = userData.users.findIndex(u => u.id == body.id)
      if (index !== -1) {
        userData.users[index] = { ...userData.users[index], ...body }
        return {
          code: 200,
          msg: '操作成功',
          data: null
        }
      } else {
        return {
          code: 404,
          msg: '用户不存在'
        }
      }
    }
  },
  
  // 删除用户
  {
    url: RegExp('/api/user/delete/.*'),
    method: 'delete',
    response: ({ url }) => {
      const id = url.split('/').pop()
      const index = userData.users.findIndex(u => u.id == id)
      if (index !== -1) {
        userData.users.splice(index, 1)
        return {
          code: 200,
          msg: '操作成功',
          data: null
        }
      } else {
        return {
          code: 404,
          msg: '用户不存在'
        }
      }
    }
  },
  
  // 更新用户状态
  {
    url: RegExp('/api/user/updateStatus/.*'),
    method: 'put',
    response: ({ url, query }) => {
      const id = url.split('/').pop()
      const user = userData.users.find(u => u.id == id)
      if (user) {
        user.status = parseInt(query.status)
        return {
          code: 200,
          msg: '操作成功',
          data: null
        }
      } else {
        return {
          code: 404,
          msg: '用户不存在'
        }
      }
    }
  },
  
  // 修改密码
  {
    url: '/api/user/updatePassword',
    method: 'put',
    response: () => {
      return {
        code: 200,
        msg: '密码修改成功',
        data: null
      }
    }
  }
]